<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="分类编码" prop="categoryNo">
        <el-input v-model="queryParams.categoryNo" placeholder="请输入分类编码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="分类名称" prop="categoryName">
        <el-input v-model="queryParams.categoryName" placeholder="请输入分类名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss"
                        type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                        :default-time="['00:00:00', '23:59:59']"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
                   v-hasPermi="['basic:material-category:create']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['basic:material-category:delete']"
        >
          批量删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 参考system/dept的树形表格实现 -->
    <el-table v-loading="loading" :data="list" row-key="id"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}" :default-expand-all="isExpandAll"
              @selection-change="handleRowCheckboxChange">
      <!-- 添加ref="table"属性 -->
      <!-- 移除@expand-change事件监听，因为不再需要动态加载 -->
      <el-table-column type="selection" width="55"/>
      <el-table-column label="分类编码" prop="categoryNo"/>
      <el-table-column label="分类名称" align="center" prop="categoryName"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"
                     v-hasPermi="['basic:material-category:update']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-plus" @click="openForm(undefined, scope.row.id)"
                     v-hasPermi="['basic:material-category:create']">新增下级
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['basic:material-category:delete']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 对话框(添加 / 修改) -->
    <MaterialCategoryForm ref="formRef" @success="getList"/>
  </div>
</template>

<script>
import * as MaterialCategoryApi from '@/api/basic/materialcategory';
import MaterialCategoryForm from './MaterialCategoryForm.vue';

export default {
  name: "MaterialCategory",
  components: {
    MaterialCategoryForm,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料分类列表
      list: [],
      // 选中行
      currentRow: {},
      checkedIds: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        categoryNo: null,
        categoryName: null,
        createTime: [],
      },
      // 是否展开，默认全部展开
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        // 不设置parentId，查询所有数据
        const query = {...this.queryParams};
        // 如果有parentId参数，删除它，确保查询所有数据
        delete query.parentId;
        const res = await MaterialCategoryApi.getMaterialCategoryPage(query);

        // 修复：获取数据时使用正确的路径
        const allData = Array.isArray(res?.data) ? res.data : [];
        console.log('原始数据:', allData);

        // 构建树形结构
        const treeData = this.handleTree(allData, 0);
        console.log('树形结构数据:', treeData);
        this.list = treeData;
        this.total = res?.data?.total || 0;
      } catch (error) {
        console.error('获取分类列表失败:', error);
        this.list = [];
        this.total = 0;
      } finally {
        this.loading = false;
      }
    },

    /** 构建树形结构 */
    buildTreeW(data, parentId) {
      // 添加数据安全检查
      if (!Array.isArray(data)) {
        console.warn('buildTree: data不是数组');
        return [];
      }

      const result = [];
      const map = {};
      console.log(`开始构建树形结构，parentId: ${parentId}`);

      // 构建ID映射，方便查找父节点
      data.forEach(item => {
        map[item.id] = {
          ...item,
          children: [],
          hasChildren: false
        };
      });

      // 构建树形结构
      data.forEach(item => {
        const current = map[item.id];

        if (item.parentId === parentId) {
          // 顶级节点
          result.push(current);
        } else if (map[item.parentId]) {
          // 子级节点
          map[item.parentId].children.push(current);
          map[item.parentId].hasChildren = true;
        }
      });

      console.log('树形结构构建完成，结果:', result);
      return result;
    },

    /** 展开/折叠全部操作 */
    toggleExpandAll() {
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        // 全部展开/折叠所有行
        const table = this.$refs['table'];
        if (table) {
          if (this.isExpandAll) {
            table.toggleRowExpansion = function (row) {
              this.store.states.expandRows.push(row);
            };
          } else {
            table.toggleRowExpansion = function (row) {
              const index = this.store.states.expandRows.indexOf(row);
              if (index > -1) {
                this.store.states.expandRows.splice(index, 1);
              }
            };
          }

          // 递归处理所有行
          this.recursiveToggleExpand(table, this.list, this.isExpandAll);
        }
      });
    },

    /** 递归切换展开/折叠状态 */
    recursiveToggleExpand(table, rows, isExpand) {
      rows.forEach(row => {
        table.toggleRowExpansion(row, isExpand);
        if (row.children && row.children.length > 0) {
          this.recursiveToggleExpand(table, row.children, isExpand);
        }
      });
    },

    // 移除handleExpandChange和loadChildData方法，因为不再需要
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 添加/修改操作 */
    openForm(id, parentId) {
      // 支持传入parentId创建下级分类
      this.$refs["formRef"].open(id, parentId);
    },

    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除物料分类编号为"' + id + '"的数据项?')
      try {
        await MaterialCategoryApi.deleteMaterialCategory(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },

    /** 批量删除物料分类 */
    async handleDeleteBatch() {
      await this.$modal.confirm('是否确认删除?')
      try {
        await MaterialCategoryApi.deleteMaterialCategoryList(this.checkedIds);
        this.checkedIds = [];
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },

    handleRowCheckboxChange(records) {
      this.checkedIds = records.map((item) => item.id);
    },

    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有物料分类数据项?');
      try {
        this.exportLoading = true;
        const data = await MaterialCategoryApi.exportMaterialCategoryExcel(this.queryParams);
        this.$download.excel(data, '物料分类.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },

    /** 判断数组是否为空 */
    isEmpty(arr) {
      return !arr || arr.length === 0;
    }
  }
};
</script>

<style scoped>
/* 移除面包屑样式 */
</style>
